package cn.remexs.examples.apijson;

import apijson.framework.APIJSONApplication;
import apijson.framework.APIJSONCreator;
import apijson.orm.FunctionParser;
import apijson.orm.SQLConfig;
import cn.remexs.examples.apijson.config.CustomSQLConfig;
import cn.remexs.examples.apijson.parser.CustomFunctionParser;
import cn.remexs.examples.apijson.parser.CustomVerifier;
import apijson.orm.Verifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * SpringBootApplication 右键这个类 > Run As > Java Application
 *
 * @author Lemon
 */
@Configuration
@SpringBootApplication
public class ApiJsonApplication {

  private final class WebMvcConfigurerImplementation
    implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
      registry
        .addMapping("/**")
        .allowedOriginPatterns("*")
        .allowedMethods("*")
        .allowCredentials(true)
        .maxAge(3600);
    }
  }

  static {
    APIJSONApplication.DEFAULT_APIJSON_CREATOR =
      new APIJSONCreator() {

        @Override
			public FunctionParser createFunctionParser() {
				return new CustomFunctionParser();
			}

			@Override
			public Verifier<Long> createVerifier() {
				return new CustomVerifier();
			}

			@Override
			public SQLConfig createSQLConfig() {
				return new CustomSQLConfig();
			}
      };
  }

  public static void main(String[] args) throws Exception {
    SpringApplication.run(ApiJsonApplication.class, args);
    APIJSONApplication.init(false); // 4.4.0 以上需要这句来保证以上 static 代码块中给 DEFAULT_APIJSON_CREATOR 赋值会生效
  }

  // 支持 APIAuto 中 JavaScript 代码跨域请求 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerImplementation();
  }
  // 支持 APIAuto 中 JavaScript 代码跨域请求 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}
